package com.example.workapp;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.p2p.*;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class WifiClientActivity extends AppCompatActivity {

    private static final String TAG = "WifiServer";
    private static final int PORT = 8888;
    private WifiP2pManager wifiP2pManager;
    private WifiP2pManager.Channel channel;
    private BroadcastReceiver wifiP2pReceiver;
    private IntentFilter intentFilter;
    private ServerSocket serverSocket;
    private boolean isRunning = true;
    private  String username,filename;
    private static final int REQUEST_PERMISSION = 1;
    private boolean isGroupCreated = false; // 标志位，表示群组是否已创建
    // 显示文件接收成功的弹窗
    private AlertDialog fileReceivedDialog; // 保存 Dialog 的引用
    private int flag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi_client);
        flag = getIntent().getIntExtra("flag", 0); //

        setupBroadcastReceiver();
        checkPermissionsAndInitialize();
    }

    private void checkPermissionsAndInitialize() {
        // 需要申请的权限列表
        String[] permissions = {
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.ACCESS_FINE_LOCATION
        };

        // Android 12 及以上版本需要额外申请 NEARBY_WIFI_DEVICES 权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            permissions = new String[]{
                    Manifest.permission.ACCESS_WIFI_STATE,
                    Manifest.permission.CHANGE_WIFI_STATE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.NEARBY_WIFI_DEVICES
            };
        }

        // 检查是否已经授予所有权限
        boolean allPermissionsGranted = true;
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                allPermissionsGranted = false;
                break;
            }
        }

        if (!allPermissionsGranted) {
            // 动态申请权限
            ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSION);
        } else {
            // 权限已授予，初始化 Wi-Fi Direct
            initializeWifiDirect();
        }
    }

    private void initializeWifiDirect() {
        // 检查设备是否支持 Wi-Fi Direct
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT)) {
            Toast.makeText(this, "此设备不支持 Wi-Fi Direct", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        wifiP2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        channel = wifiP2pManager.initialize(this, getMainLooper(), null);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.e(TAG, "Wi-Fi P2P 需要位置权限");
            return;
        }

        // 检查是否已经有群组存在
        wifiP2pManager.requestGroupInfo(channel, new WifiP2pManager.GroupInfoListener() {
            @Override
            public void onGroupInfoAvailable(WifiP2pGroup group) {
                if (group != null && wifiP2pManager != null && channel != null) {
                    // 如果已经有群组存在，先删除它
                    wifiP2pManager.removeGroup(channel, new WifiP2pManager.ActionListener() {
                        @Override
                        public void onSuccess() {
                            Log.d(TAG, "现有群组已删除");
                            // 删除成功后创建新的群组
                            createNewGroup();
                        }

                        @Override
                        public void onFailure(int reason) {
                            Log.d(TAG, "删除现有群组失败: " + reason);
                        }
                    });
                } else {
                    // 如果没有群组存在，直接创建新的群组
                    createNewGroup();
                }
            }
        });
    }

    private void createNewGroup() {
        //createGroup 是异步的
        wifiP2pManager.createGroup(channel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                isGroupCreated = true;
                Log.d(TAG, "群组创建成功");
//                Toast.makeText(WifiClientActivity.this, "群组创建成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int reason) {
                isGroupCreated = false;
//                Log.d(TAG, "群组创建失败: " + reason);
            }
        });
    }

    // 监听 WiFi P2P 连接状态的广播接收器
    private void setupBroadcastReceiver() {
        wifiP2pReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                //设备连接到另一个设备或断开连接
                if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
                    if (wifiP2pManager == null) return;

                    NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
                    if (networkInfo != null && networkInfo.isConnected()) {
                        // 检查连接信息，确认是否为 Group Owner
                        wifiP2pManager.requestConnectionInfo(channel, connectionInfo -> {
                            if (connectionInfo.groupFormed && isGroupCreated) {
                                if (connectionInfo.isGroupOwner) {
                                    Log.d(TAG, "本机是 Group Owner，客户端已连接");
                                    if (serverSocket == null || serverSocket.isClosed()){
                                        startServerSocketForFileReceive();
                                    }
                                } else {
                                    Log.d(TAG, "本机不是 Group Owner");
                                }
                            }
                        });
                    } else {
                        Log.d(TAG, "Wi-Fi P2P 连接已断开");
                        stopServer(); // 断开连接时关闭 ServerSocket
                    }
                    //对等设备列表发生了变化
                } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
                    //已经连接设备
                    if (isGroupCreated && serverSocket != null && !serverSocket.isClosed()) {
                        Log.d(TAG, "已连接，忽略设备发现广播");
                        return;
                    }
                    // 处理设备列表变化
                    if (ActivityCompat.checkSelfPermission(WifiClientActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        wifiP2pManager.requestPeers(channel, peerList -> {
                            Log.d(TAG, "发现 " + peerList.getDeviceList().size() + " 个设备");
                        });
                    }
                }
            }
        };

        intentFilter = new IntentFilter();
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        registerReceiver(wifiP2pReceiver, intentFilter);
    }

    // 启动 ServerSocket 等待客户端连接
    private void startServerSocketForFileReceive() {
        Log.d(TAG, "开始startServerSocketForFileReceive");
//        避免设备反复连接/断开，反复调用startServerSocketForFileReceive()，建立多个serversocket
        if (serverSocket != null && !serverSocket.isClosed()) {
            Log.d(TAG, "ServerSocket 已经在运行，跳过重复启动");
            return; // 如果 ServerSocket 已经在运行，则不再启动
        }

        new Thread(() -> {
            try {
//                // 确保之前的 ServerSocket 已关闭
//                if (serverSocket != null && !serverSocket.isClosed()) {
//                    serverSocket.close();
//                }
                serverSocket = new ServerSocket(PORT);
                Log.d(TAG, "服务器已启动，等待客户端连接...");
//                runOnUiThread(() -> Toast.makeText(WifiClientActivity.this, "服务器已启动，等待客户端连接...", Toast.LENGTH_SHORT).show());

                while (isRunning) {
                    Socket clientSocket = serverSocket.accept();  // 阻塞等待客户端连接
                    String clientIp = clientSocket.getInetAddress().getHostAddress();  // 获取客户端 IP
                    Log.d(TAG, "客户端连接成功，开始接收文件...");
                    if (flag == 0) {
                        receiveFileFromClient(clientSocket);
                    }else if(flag==1){
                        //editFile
//                        filename=getIntent().getStringExtra("filename");
                        // 读取文件名
                        BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
                        System.out.println("客户端已连接：" + clientSocket.getInetAddress());
                        // 读取客户端消息
                        filename = reader.readLine();
                        System.out.println("收到客户端消息：" + filename);
                        // 发送回复
                        writer.println("收到: " + filename);
                        clientSocket.close();

                        username=getIntent().getStringExtra("username");
                        Log.d(TAG,"filename "+filename+" username "+username);
                        Intent webIntent=new Intent(WifiClientActivity.this,WebActivity.class);
                        webIntent.putExtra("filename",filename);
                        webIntent.putExtra("username",username);
                        webIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(webIntent);
                    }else if(flag==2){
                        //传视频流
                        BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
                        System.out.println("客户端已连接：" + clientSocket.getInetAddress());
                        // 读取客户端消息
                        String msg = reader.readLine();
                        System.out.println("收到客户端消息：" + msg);
                        // 发送回复
                        writer.println("收到: " + msg);
                        clientSocket.close();

                        Intent screenWebIntent=new Intent(WifiClientActivity.this,screen_web_activity.class);
                        screenWebIntent.putExtra("recv_ip",clientIp);
                        screenWebIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(screenWebIntent);
                    }
                    serverSocket.close();
                    Log.d(TAG, "服务器已关闭");
                }
            } catch (IOException e) {
                Log.e(TAG, "服务器错误: " + e.getMessage());
//                runOnUiThread(() -> Toast.makeText(WifiClientActivity.this, "服务器连接失败", Toast.LENGTH_SHORT).show());
            }
        }).start();
    }

    // 从字节数组转换为整数
    private static int bytesToInt(byte[] bytes) {
        return ByteBuffer.wrap(bytes).getInt();
    }

    // 从字节数组转换为长
    private static long bytesToLong(byte[] bytes) {
        return ByteBuffer.wrap(bytes).getLong();
    }

    // 接收文件
    private void receiveFileFromClient(Socket clientSocket) {
        new Thread(() -> {
            try {
                InputStream inputStream = clientSocket.getInputStream();
                DataInputStream dataInputStream = new DataInputStream(inputStream);

                // 1. 读取 MIME 类型长度
                byte[] mimeTypeLengthBytes = new byte[4];
                dataInputStream.readFully(mimeTypeLengthBytes);
                int mimeTypeLength = bytesToInt(mimeTypeLengthBytes);

                // 2. 读取 MIME 类型
               byte[] mimeTypeBytes = new byte[mimeTypeLength];
                dataInputStream.readFully(mimeTypeBytes);
                String mimeType = new String(mimeTypeBytes, StandardCharsets.UTF_8);
                Log.d(TAG, "文件类型: " + mimeType);

                // 3. 读取文件大小
                byte[] fileSizeBytes = new byte[8];
                dataInputStream.readFully(fileSizeBytes);
                long fileSize = bytesToLong(fileSizeBytes);
                Log.d(TAG, "文件大小: " + fileSize + " 字节");

                // 生成文件路径
                String fileExtension = getFileExtensionFromMimeType(mimeType);
                File receivedFile = new File(getExternalFilesDir(null), "received_file_" + System.currentTimeMillis() + fileExtension);
                FileOutputStream fileOutputStream = new FileOutputStream(receivedFile);

                byte[] buffer = new byte[1024];  // 增大缓冲区，提高效率
                int bytesRead;
                long totalBytesRead = 0;

                // 4. 接收文件内容
                while (totalBytesRead < fileSize && (bytesRead = dataInputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;
                    Log.d(TAG, "已接收: " + totalBytesRead + "/" + fileSize + " 字节");
                }

                fileOutputStream.close();

                // 5. 发送确认信号
//                OutputStream outputStream = clientSocket.getOutputStream();
//                outputStream.write(new byte[]{1}); // 发送确认信号
//                outputStream.flush();

                dataInputStream.close();
                inputStream.close();
                clientSocket.close();

                // 文件接收成功，弹出提示弹窗
                runOnUiThread(() -> showFileReceivedDialog(receivedFile));
                Log.d(TAG, "文件接收完成: " + receivedFile.getAbsolutePath());

            } catch (IOException e) {
                Log.e(TAG, "文件接收失败: " + e.getMessage());
                runOnUiThread(() -> Toast.makeText(WifiClientActivity.this, "文件接收失败", Toast.LENGTH_SHORT).show());
            }
        }).start();
    }



    private void showFileReceivedDialog(File receivedFile) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("文件接收成功");
        builder.setMessage("文件已保存到: " + receivedFile.getAbsolutePath());

        // 打开文件所在位置
        builder.setPositiveButton("打开", (dialog, which) -> {
            openFileLocation(receivedFile);
            finish();  // 完成后关闭活动
        });

        // 取消操作
        builder.setNegativeButton("取消", (dialog, which) -> {
            dialog.dismiss();
            finish();  // 完成后关闭活动
        });


        // 显示弹窗
        fileReceivedDialog = builder.create();
        fileReceivedDialog.show();
    }

    // 打开文件所在位置
    private void openFileLocation(File file) {
        if (!file.exists()) {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri fileUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", file); // 使用 FileProvider 获取 Uri
        Log.d(TAG, "fileURI: " + fileUri);


        // 根据文件类型设置 MIME 类型
        String mimeType = getMimeType(file.getAbsolutePath());
        Log.d(TAG, "MimeTypr: " + mimeType);

        intent.setDataAndType(fileUri, mimeType);

        // 授予临时读取权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        // 启动文件管理器
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        } else {
            Toast.makeText(this, "未找到文件管理器", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "未找到支持 MIME 类型 " + mimeType + " 的文件");
        }
    }

    // 获取文件的 MIME 类型
    private String getMimeType(String filePath) {
        String extension = filePath.substring(filePath.lastIndexOf(".") + 1);
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
    }
    // 根据 MIME 类型获取文件扩展名
    private String getFileExtensionFromMimeType(String mimeType) {
        if (mimeType.equals("application/pdf")) return ".pdf";
        if (mimeType.equals("image/jpeg")) return ".jpg";
        if (mimeType.equals("image/png")) return ".png";
        if (mimeType.equals("text/plain")) return ".txt";
        if (mimeType.equals("application/vnd.ms-excel")) return ".xls";
        if (mimeType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) return ".xlsx";
        if (mimeType.equals("application/msword")) return ".doc";
        if (mimeType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) return ".docx";
        if(mimeType.equals("application/xml") || mimeType.equals("text/xml")) return".xml";
        return ".bin"; // 默认二进制文件扩展名
    }

    // Activity 从后台回到前台时调用（例如用户从其他应用返回当前 Activity）。
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(wifiP2pReceiver, intentFilter);
    }

    //当 Activity 进入后台时调用（例如用户按下 Home 键或切换到其他应用）
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(wifiP2pReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isRunning = false;
        stopServer(); // 关闭 ServerSocket
        // 解除注册 BroadcastReceiver
        if (wifiP2pReceiver != null) {
            unregisterReceiver(wifiP2pReceiver);
        }
        // 关闭 Dialog
        if (fileReceivedDialog != null && fileReceivedDialog.isShowing()) {
            fileReceivedDialog.dismiss();
        }
    }

    public void stopServer() {
//        isRunning = false; // 停止服务器循环
        if (serverSocket != null && !serverSocket.isClosed()) {
            try {
                serverSocket.close();
                Log.d(TAG, "服务器已关闭");
            } catch (IOException e) {
                Log.e(TAG, "关闭 ServerSocket 失败: " + e.getMessage());
            }
        }
    }

    // 处理权限申请结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION) {
            boolean allPermissionsGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }

            if (allPermissionsGranted) {
                // 权限已授予，初始化 Wi-Fi Direct
                initializeWifiDirect();
            } else {
                // 权限被拒绝，提示用户
                Toast.makeText(this, "需要权限才能使用 Wi-Fi Direct 功能", Toast.LENGTH_SHORT).show();
                finish(); // 关闭 Activity 或采取其他措施
            }
        }
    }
}